#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
企业问题生成模块
支持根据不同企业生成各种类型的提问，包括舆情监测、企业分析等
"""

import asyncio
import aiohttp
import json
import random
import time
from typing import Dict, List, Optional, Any, Union
from dataclasses import dataclass, field
from enum import Enum


class QuestionType(Enum):
    """问题类型枚举"""
    NEGATIVE_NEWS = "negative_news"  # 负面新闻
    POSITIVE_NEWS = "positive_news"  # 正面新闻
    FINANCIAL_INFO = "financial_info"  # 财务信息
    MARKET_ANALYSIS = "market_analysis"  # 市场分析
    PRODUCT_INFO = "product_info"  # 产品信息
    LEADERSHIP = "leadership"  # 领导层信息
    COMPETITIVE_ANALYSIS = "competitive_analysis"  # 竞争分析
    TECHNOLOGY = "technology"  # 技术能力
    REPUTATION = "reputation"  # 品牌声誉
    INVESTMENT = "investment"  # 投资相关
    REGULATION = "regulation"  # 监管合规
    ESG = "esg"  # ESG相关


@dataclass
class Company:
    """企业信息类"""
    name: str
    industry: str
    description: str = ""
    competitors: List[str] = field(default_factory=list)
    keywords: List[str] = field(default_factory=list)
    founded_year: Optional[int] = None
    headquarters: str = ""
    
    def __post_init__(self):
        # 自动生成一些关键词
        if not self.keywords:
            self.keywords = [self.name]


@dataclass
class GeneratedQuestion:
    """生成的问题数据类"""
    question: str
    question_type: QuestionType
    company: str
    is_inspirational: bool = False
    inspiration_prompt: str = ""
    metadata: Dict[str, Any] = field(default_factory=dict)


class DeepSeekProvider:
    """DeepSeek API服务提供商"""
    
    def __init__(self, api_key: str, base_url: str = "https://api.deepseek.com/v1"):
        self.api_key = api_key
        self.base_url = base_url
    
    async def generate_inspirational_prompt(self, company: Company, question_type: QuestionType, 
                                          session: aiohttp.ClientSession) -> str:
        """使用DeepSeek生成启发式提示词"""
        try:
            url = f"{self.base_url}/chat/completions"
            headers = {
                'Authorization': f'Bearer {self.api_key}',
                'Content-Type': 'application/json'
            }
            
            # 构建提示词生成请求 - 专注于极端情况检测
            system_prompt = f"""你是一个专业的企业风险分析专家，专门负责极端情况检测和舆情压力测试。请根据给定的企业信息和问题类型，生成3-5个具有挑战性、尖锐性的问题，重点关注潜在风险和负面因素。

企业信息：
- 公司名称：{company.name}
- 行业：{company.industry}
- 描述：{company.description}
- 竞争对手：{', '.join(company.competitors) if company.competitors else '无'}
- 关键词：{', '.join(company.keywords)}

问题类型：{question_type.value}

分析要求：
1. **重点挖掘潜在风险和负面因素** - 假设最坏情况，寻找薄弱环节
2. **关注争议性和敏感话题** - 涉及法律风险、道德争议、监管问题等
3. **压力测试思维** - 模拟舆情危机、竞争威胁、市场冲击等极端场景
4. **具体且尖锐** - 问题要具体、直接，不回避敏感问题
5. **基于真实风险** - 结合行业特点和企业背景，提出可能存在的实际风险

特别关注领域：
- 财务造假、内幕交易、关联交易风险
- 数据泄露、隐私侵犯、安全漏洞
- 垄断行为、不正当竞争、监管违规
- 劳资纠纷、裁员争议、员工权益
- 环境污染、社会责任缺失
- 技术伦理、算法偏见、平台责任
- 供应链风险、合作伙伴问题
- 高管丑闻、治理失效、股东纠纷

返回格式：纯文本，每个问题一行，问题要尖锐且具有挑战性。"""

            payload = {
                "model": "deepseek-chat",
                "messages": [
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": f"请为{company.name}生成关于{question_type.value}的启发性问题"}
                ],
                "temperature": 0.8,
                "max_tokens": 1000
            }
            
            async with session.post(url, json=payload, headers=headers) as response:
                if response.status == 200:
                    data = await response.json()
                    if 'choices' in data and len(data['choices']) > 0:
                        return data['choices'][0]['message']['content'].strip()
                else:
                    error_text = await response.text()
                    print(f"DeepSeek API错误: {response.status} - {error_text}")
                    return ""
                    
        except Exception as e:
            print(f"DeepSeek API调用异常: {e}")
            return ""


class QuestionTemplateManager:
    """问题模板管理器"""
    
    def __init__(self):
        self.templates = {
            QuestionType.NEGATIVE_NEWS: [
                "{company}最近有什么负面新闻吗？",
                "{company}公司目前面临哪些争议和批评？",
                "有关{company}的负面报道和舆情风险有哪些？",
                "{company}最近是否涉及任何丑闻或法律问题？",
                "网上对{company}有什么负面评价和投诉？",
                "{company}在产品质量、服务等方面有哪些问题？",
                "{company}是否存在财务造假、违规经营等问题？",
                "{company}是否存在数据泄露、隐私侵犯等安全事件？",
                "{company}是否涉及垄断行为、不正当竞争或监管违规？",
                "{company}在劳资纠纷、员工权益保护方面有什么争议？",
                "{company}的管理层是否存在腐败、利益输送等问题？",
                "{company}是否因环境污染、社会责任缺失受到指控？"
            ],
            QuestionType.POSITIVE_NEWS: [
                "{company}最近有什么好消息或积极进展？",
                "{company}公司有哪些值得关注的成就和突破？",
                "{company}在行业中有什么创新和领先优势？",
                "{company}最近获得了哪些奖项或认可？",
                "{company}的正面新闻和市场表现如何？",
                "{company}在社会责任方面有什么积极表现？"
            ],
            QuestionType.FINANCIAL_INFO: [
                "{company}的最新财务报告显示了什么？",
                "{company}的盈利能力和财务状况如何？",
                "{company}的股价表现和市值变化怎样？",
                "{company}的营收增长趋势是什么？",
                "{company}的债务状况和现金流如何？",
                "{company}的投资价值和财务风险评估如何？",
                "{company}是否存在财务造假、虚增收入或隐瞒债务的风险？",
                "{company}的审计机构是否发现重大财务问题或内控缺陷？",
                "{company}是否存在关联交易、利益输送等财务违规行为？",
                "{company}的资金链是否存在断裂风险？现金流是否可持续？",
                "{company}的财务数据是否与行业同行存在异常差异？"
            ],
            QuestionType.MARKET_ANALYSIS: [
                "{company}在{industry}行业中的市场地位如何？",
                "{company}的市场份额和竞争优势是什么？",
                "{company}面临的主要市场挑战有哪些？",
                "{company}的目标市场和客户群体分析",
                "{company}在国内外市场的表现差异",
                "{company}的市场战略和发展规划如何？"
            ],
            QuestionType.PRODUCT_INFO: [
                "{company}的主要产品和服务有哪些？",
                "{company}最新推出的产品有什么特点？",
                "{company}的产品在市场上的口碑如何？",
                "{company}的产品技术水平和创新能力怎样？",
                "{company}产品的用户评价和市场反馈如何？",
                "{company}的产品线布局和发展方向是什么？"
            ],
            QuestionType.LEADERSHIP: [
                "{company}的创始人和核心管理团队是谁？",
                "{company}CEO的背景和管理风格如何？",
                "{company}高管团队最近有什么变动？",
                "{company}的企业文化和管理理念是什么？",
                "{company}领导层的决策能力和战略眼光如何？",
                "{company}的治理结构和股权结构情况",
                "{company}的高管是否存在贪腐、违法违规或道德问题？",
                "{company}的创始人或CEO是否有争议性言论或行为？",
                "{company}的管理层是否存在频繁离职、内斗或治理失效？",
                "{company}是否存在大股东操控、中小股东权益受损的问题？",
                "{company}的决策机制是否透明？是否存在暗箱操作？"
            ],
            QuestionType.COMPETITIVE_ANALYSIS: [
                "{company}的主要竞争对手有哪些？",
                "{company}与{competitors}相比有什么优劣势？",
                "{company}在行业竞争中的差异化策略是什么？",
                "{company}如何应对激烈的市场竞争？",
                "{company}的竞争壁垒和核心竞争力是什么？",
                "{company}在竞争中的市场表现如何？"
            ],
            QuestionType.TECHNOLOGY: [
                "{company}的核心技术和研发能力如何？",
                "{company}在技术创新方面有什么突破？",
                "{company}的研发投入和技术团队规模如何？",
                "{company}拥有哪些重要的技术专利？",
                "{company}的技术发展路线图是什么？",
                "{company}在数字化转型方面的进展如何？"
            ],
            QuestionType.REPUTATION: [
                "{company}的品牌知名度和美誉度如何？",
                "公众对{company}的整体印象和评价是什么？",
                "{company}在媒体和社交平台上的声誉如何？",
                "{company}的品牌价值和影响力评估",
                "{company}在客户满意度方面的表现如何？",
                "{company}的企业形象和公关策略效果怎样？"
            ],
            QuestionType.INVESTMENT: [
                "{company}值得投资吗？投资风险如何？",
                "{company}的融资历史和投资者情况",
                "{company}的投资回报和增长潜力分析",
                "{company}IPO或上市的相关信息",
                "投资{company}需要关注哪些关键指标？",
                "{company}的估值水平是否合理？"
            ],
            QuestionType.REGULATION: [
                "{company}是否遵守相关法律法规？",
                "{company}面临哪些监管风险和合规要求？",
                "{company}是否涉及反垄断或监管调查？",
                "{company}的合规体系和风险管控如何？",
                "{company}在数据隐私保护方面的表现",
                "{company}如何应对监管政策变化？",
                "{company}是否存在系统性违法违规行为？监管部门是否已介入？",
                "{company}是否面临重大罚款、业务整顿或牌照吊销风险？",
                "{company}的业务模式是否存在法律灰色地带或监管空白？",
                "{company}是否涉及洗钱、逃税或其他金融犯罪问题？",
                "{company}在海外市场是否面临制裁、禁令或法律诉讼？"
            ],
            QuestionType.ESG: [
                "{company}的社会责任履行情况如何？",
                "{company}的公司治理和透明度水平",
                "{company}在ESG评级中的表现如何？",
                "{company}的可持续发展战略和实践",
                "{company}在员工权益保护方面的措施"
            ]
        }
    
    def get_templates(self, question_type: QuestionType) -> List[str]:
        """获取指定类型的问题模板"""
        return self.templates.get(question_type, [])
    
    def generate_question_from_template(self, company: Company, question_type: QuestionType) -> str:
        """从模板生成问题"""
        templates = self.get_templates(question_type)
        if not templates:
            return f"关于{company.name}的{question_type.value}相关信息"
        
        template = random.choice(templates)
        
        # 替换模板中的变量
        question = template.format(
            company=company.name,
            industry=company.industry,
            competitors=', '.join(company.competitors[:3]) if company.competitors else '主要竞争对手'
        )
        
        return question


class QuestionGenerator:
    """问题生成器主类"""
    
    def __init__(self, deepseek_api_key: str = None):
        self.companies: Dict[str, Company] = {}
        self.template_manager = QuestionTemplateManager()
        self.deepseek_provider = DeepSeekProvider(deepseek_api_key) if deepseek_api_key else None
        
        # 预置一些常见企业
        self._setup_default_companies()
    
    def _setup_default_companies(self):
        """设置默认的企业数据"""
        default_companies = [
            Company(
                name="腾讯",
                industry="互联网科技",
                description="中国领先的互联网增值服务提供商",
                competitors=["阿里巴巴", "字节跳动", "百度"],
                keywords=["微信", "QQ", "游戏", "云服务"],
                founded_year=1998,
                headquarters="深圳"
            ),
            Company(
                name="阿里巴巴",
                industry="电子商务",
                description="全球领先的电子商务和云计算公司",
                competitors=["腾讯", "京东", "拼多多"],
                keywords=["淘宝", "天猫", "支付宝", "阿里云"],
                founded_year=1999,
                headquarters="杭州"
            ),
            Company(
                name="字节跳动",
                industry="互联网内容",
                description="全球化的移动互联网平台",
                competitors=["腾讯", "快手", "百度"],
                keywords=["抖音", "今日头条", "TikTok"],
                founded_year=2012,
                headquarters="北京"
            ),
            Company(
                name="比亚迪",
                industry="新能源汽车",
                description="全球领先的新能源汽车制造商",
                competitors=["特斯拉", "蔚来", "理想"],
                keywords=["电动汽车", "电池", "新能源"],
                founded_year=1995,
                headquarters="深圳"
            ),
            Company(
                name="美团",
                industry="本地生活服务",
                description="中国领先的生活服务电子商务平台",
                competitors=["饿了么", "滴滴", "大众点评"],
                keywords=["外卖", "酒店", "出行"],
                founded_year=2010,
                headquarters="北京"
            )
        ]
        
        for company in default_companies:
            self.companies[company.name] = company
    
    def add_company(self, company: Company):
        """添加企业"""
        self.companies[company.name] = company
    
    def get_company(self, name: str) -> Optional[Company]:
        """获取企业信息"""
        return self.companies.get(name)
    
    def list_companies(self) -> List[str]:
        """列出所有企业名称"""
        return list(self.companies.keys())
    
    def generate_template_question(self, company_name: str, question_type: QuestionType) -> Optional[GeneratedQuestion]:
        """生成模板问题"""
        company = self.get_company(company_name)
        if not company:
            return None
        
        question = self.template_manager.generate_question_from_template(company, question_type)
        
        return GeneratedQuestion(
            question=question,
            question_type=question_type,
            company=company_name,
            is_inspirational=False
        )
    
    async def generate_inspirational_question(self, company_name: str, question_type: QuestionType) -> Optional[GeneratedQuestion]:
        """生成启发式问题"""
        if not self.deepseek_provider:
            print("⚠️ 未配置DeepSeek API，无法生成启发式问题")
            return None
        
        company = self.get_company(company_name)
        if not company:
            return None
        
        timeout = aiohttp.ClientTimeout(total=30)
        async with aiohttp.ClientSession(timeout=timeout) as session:
            inspiration_prompt = await self.deepseek_provider.generate_inspirational_prompt(
                company, question_type, session
            )
        
        if not inspiration_prompt:
            # 如果启发式生成失败，回退到模板模式
            print(f"⚠️ 启发式问题生成失败，回退到模板模式")
            template_question = self.generate_template_question(company_name, question_type)
            if template_question:
                template_question.is_inspirational = False
            return template_question
        
        # 解析DeepSeek返回的多个问题，随机选择一个
        questions = [q.strip() for q in inspiration_prompt.split('\n') if q.strip()]
        selected_question = random.choice(questions) if questions else inspiration_prompt
        
        return GeneratedQuestion(
            question=selected_question,
            question_type=question_type,
            company=company_name,
            is_inspirational=True,
            inspiration_prompt=inspiration_prompt,
            metadata={"total_generated": len(questions)}
        )
    
    async def generate_batch_questions(self, company_names: List[str], question_types: List[QuestionType], 
                                     use_inspiration: bool = False, max_per_company: int = 2, 
                                     min_total_questions: int = 30) -> List[GeneratedQuestion]:
        """批量生成问题 - 确保生成足够多的问题进行极端情况检测"""
        questions = []
        
        # 第一轮：为每个企业生成基础问题
        for company_name in company_names:
            company = self.get_company(company_name)
            if not company:
                print(f"⚠️ 企业 {company_name} 不存在，跳过")
                continue
            
            # 确保覆盖所有问题类型
            for question_type in question_types:
                # 生成多个不同的问题
                questions_for_type = []
                
                # 生成模板问题（多个尝试以获得不同的问题）
                for attempt in range(3):
                    template_q = self.generate_template_question(company_name, question_type)
                    if template_q and template_q.question not in [q.question for q in questions_for_type]:
                        questions_for_type.append(template_q)
                
                # 如果启用了灵感问题，生成AI增强的问题
                if use_inspiration and self.deepseek_provider:
                    try:
                        inspiration_q = await self.generate_inspirational_question(company_name, question_type)
                        if inspiration_q:
                            # DeepSeek可能返回多个问题，使用改进的解析逻辑
                            inspiration_text = inspiration_q.inspiration_prompt
                            if inspiration_text:
                                # 使用正则表达式解析编号的问题
                                import re
                                question_pattern = r'^(\d+\.\s*)'
                                lines = inspiration_text.split('\n')
                                current_question = ""
                                parsed_questions = []
                                
                                for line in lines:
                                    line = line.strip()
                                    if re.match(question_pattern, line):
                                        # 如果当前问题非空，添加到列表
                                        if current_question.strip():
                                            parsed_questions.append(current_question.strip())
                                        # 开始新问题，去掉数字编号
                                        current_question = re.sub(question_pattern, '', line)
                                    else:
                                        # 继续当前问题
                                        if line:
                                            current_question += " " + line
                                
                                # 添加最后一个问题
                                if current_question.strip():
                                    parsed_questions.append(current_question.strip())
                                
                                # 将解析到的问题添加到列表中
                                for i, q_text in enumerate(parsed_questions[:3]):  # 最多取3个
                                    if q_text not in [q.question for q in questions_for_type]:
                                        enhanced_q = GeneratedQuestion(
                                            question=q_text,
                                            question_type=question_type,
                                            company=company_name,
                                            is_inspirational=True,
                                            inspiration_prompt=inspiration_text,
                                            metadata={"source": "deepseek_enhanced", "batch_index": i, "parsed_count": len(parsed_questions)}
                                        )
                                        questions_for_type.append(enhanced_q)
                    except Exception as e:
                        print(f"⚠️ 灵感问题生成失败: {e}")
                
                # 添加该类型的所有问题
                questions.extend(questions_for_type)
        
        # 第二轮：如果问题数量不足，生成更多问题
        if len(questions) < min_total_questions:
            print(f"🔄 当前生成 {len(questions)} 个问题，不足 {min_total_questions} 个，正在生成更多...")
            
            additional_needed = min_total_questions - len(questions)
            all_types = list(QuestionType)
            
            # 扩展问题类型和企业组合
            for _ in range(additional_needed):
                # 随机选择企业和问题类型
                company_name = random.choice(company_names)
                question_type = random.choice(all_types)
                
                # 生成额外的问题
                if use_inspiration and self.deepseek_provider and random.random() < 0.7:  # 70%概率使用AI
                    try:
                        extra_q = await self.generate_inspirational_question(company_name, question_type)
                        if extra_q and extra_q.question not in [q.question for q in questions]:
                            questions.append(extra_q)
                    except:
                        # 失败时回退到模板
                        extra_q = self.generate_template_question(company_name, question_type)
                        if extra_q and extra_q.question not in [q.question for q in questions]:
                            questions.append(extra_q)
                else:
                    extra_q = self.generate_template_question(company_name, question_type)
                    if extra_q and extra_q.question not in [q.question for q in questions]:
                        questions.append(extra_q)
        
        print(f"✅ 最终生成 {len(questions)} 个问题")
        return questions
    
    def generate_random_questions(self, count: int = 10, use_inspiration: bool = False) -> List[GeneratedQuestion]:
        """随机生成问题"""
        if not self.companies:
            return []
        
        questions = []
        all_types = list(QuestionType)
        
        for _ in range(count):
            company_name = random.choice(list(self.companies.keys()))
            question_type = random.choice(all_types)
            
            if use_inspiration:
                # 异步方法需要在事件循环中运行
                try:
                    loop = asyncio.get_event_loop()
                    question = loop.run_until_complete(
                        self.generate_inspirational_question(company_name, question_type)
                    )
                except RuntimeError:
                    # 如果没有事件循环，使用模板模式
                    question = self.generate_template_question(company_name, question_type)
            else:
                question = self.generate_template_question(company_name, question_type)
            
            if question:
                questions.append(question)
        
        return questions
    
    def export_questions(self, questions: List[GeneratedQuestion], format: str = "json") -> str:
        """导出问题列表"""
        if format.lower() == "json":
            data = []
            for q in questions:
                data.append({
                    "question": q.question,
                    "type": q.question_type.value,
                    "company": q.company,
                    "inspirational": q.is_inspirational,
                    "metadata": q.metadata
                })
            return json.dumps(data, ensure_ascii=False, indent=2)
        
        elif format.lower() == "txt":
            lines = []
            for i, q in enumerate(questions, 1):
                inspiration_mark = "✨" if q.is_inspirational else "📝"
                lines.append(f"{i}. {inspiration_mark} [{q.company}] {q.question}")
            return "\n".join(lines)
        
        else:
            return str(questions)
    
    def print_questions(self, questions: List[GeneratedQuestion]):
        """格式化打印问题列表"""
        if not questions:
            print("❌ 没有生成任何问题")
            return
        
        print(f"\n{'='*80}")
        print(f"📋 生成的问题列表 (共{len(questions)}个)")
        print(f"{'='*80}")
        
        # 按企业分组显示
        by_company = {}
        for q in questions:
            if q.company not in by_company:
                by_company[q.company] = []
            by_company[q.company].append(q)
        
        for company, company_questions in by_company.items():
            print(f"\n🏢 {company} ({len(company_questions)}个问题)")
            print("-" * 60)
            
            for i, q in enumerate(company_questions, 1):
                inspiration_mark = "✨启发式" if q.is_inspirational else "📝模板"
                type_name = q.question_type.value
                print(f"  {i}. {inspiration_mark} [{type_name}]")
                print(f"     {q.question}")
                
                if q.is_inspirational and q.metadata.get('total_generated'):
                    print(f"     💡 共生成{q.metadata['total_generated']}个候选问题")
    
    def get_statistics(self, questions: List[GeneratedQuestion]) -> Dict[str, Any]:
        """获取问题生成统计信息"""
        if not questions:
            return {}
        
        stats = {
            "total_questions": len(questions),
            "inspirational_count": sum(1 for q in questions if q.is_inspirational),
            "template_count": sum(1 for q in questions if not q.is_inspirational),
            "companies_covered": len(set(q.company for q in questions)),
            "question_types": {},
            "company_distribution": {}
        }
        
        # 统计问题类型分布
        for q in questions:
            type_name = q.question_type.value
            stats["question_types"][type_name] = stats["question_types"].get(type_name, 0) + 1
        
        # 统计企业分布
        for q in questions:
            stats["company_distribution"][q.company] = stats["company_distribution"].get(q.company, 0) + 1
        
        stats["inspiration_rate"] = stats["inspirational_count"] / stats["total_questions"] if stats["total_questions"] > 0 else 0
        
        return stats


# 便捷函数
def create_question_generator(deepseek_api_key: str = None) -> QuestionGenerator:
    """创建问题生成器实例"""
    return QuestionGenerator(deepseek_api_key)


if __name__ == "__main__":
    # 示例使用
    async def main():
        # 创建问题生成器（不使用DeepSeek）
        generator = create_question_generator()
        
        print("🎯 企业问题生成器演示")
        print("=" * 60)
        
        # 列出可用企业
        print("📊 可用企业:")
        for company in generator.list_companies():
            print(f"   • {company}")
        
        # 生成模板问题
        print("\n📝 模板问题示例:")
        template_questions = []
        for company in ["腾讯", "阿里巴巴", "比亚迪"][:2]:
            for qtype in [QuestionType.NEGATIVE_NEWS, QuestionType.MARKET_ANALYSIS]:
                q = generator.generate_template_question(company, qtype)
                if q:
                    template_questions.append(q)
        
        generator.print_questions(template_questions)
        
        # 统计信息
        stats = generator.get_statistics(template_questions)
        print(f"\n📈 统计信息:")
        print(f"   • 总问题数: {stats['total_questions']}")
        print(f"   • 覆盖企业: {stats['companies_covered']}")
        print(f"   • 启发式比例: {stats['inspiration_rate']:.1%}")
    
    # 运行示例
    print("🎯 企业问题生成模块已加载完成！")
    print("💡 使用说明:")
    print("   1. 创建问题生成器: generator = create_question_generator()")
    print("   2. 生成模板问题: generator.generate_template_question(company, type)")
    print("   3. 生成启发式问题: await generator.generate_inspirational_question(company, type)")
    print("   4. 配置DeepSeek API密钥以启用启发式模式")
    
    # asyncio.run(main()) 